package info.aquaball.service.turnierservice;

import info.aquaball.data.Turnier;
import info.aquaball.data.TurnierImpl;
import info.aquaball.service.exception.CouldNotStoreException;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class TurnierServiceImpl implements TurnierService {

	@Override
	public List<Turnier> getAll() {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("Turnier");
		PreparedQuery prepare = datastore.prepare(query);

		List<Turnier> result = new ArrayList<Turnier>();
		for (Entity entity : prepare.asIterable()) {
			Turnier turnier = new TurnierImpl(entity);
			result.add(turnier);
		}
		return result;
	}

	@Override
	public void store(Turnier turnier) throws CouldNotStoreException {
		Entity entity = turnier.convertToEntity();
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(entity);
	}

	@Override
	public void delete(String key) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.delete(KeyFactory.stringToKey(key));
	}
}
